package com.kchouse.mine;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.bean.MyRecommend;
import com.kchouse.bean.OrderItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.BaseApp;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.common.SharedPreferencesUtil;
import com.kchouse.common.ToastUtils;
import com.kchouse.view.QRCode;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

import static cn.finalteam.toolsfinal.BitmapUtils.drawableToBitmap;

public class RecommendActivity extends BaseActivity implements View.OnClickListener {

    private RecommendActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private RadioGroup rg_item;
    private RadioButton rb_item1;
    private RadioButton rb_item2;
    private View lay_1;
    private View lay_2;
    private ImageView iv_qcode;
    private String qrUrl;
    private Button bt_item;
    private Bitmap bp;
    private ListView lv_item;
    private TextView tv_num;
    private TextView tv_totalCash;
    private ArrayList<MyRecommend> list = new ArrayList<>();
    private LvAdapter adapter;
    private StringBuffer sb = new StringBuffer();
    private Intent intent;
    private View ll_view;
    private View ll_item1;
    private View ll_item2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommend);

        mContent = this;
        intiData();
        intiView();





    }

    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("推荐有礼");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        lay_1 = findViewById(R.id.lay_1);
        lay_2 = findViewById(R.id.lay_2);
        iv_qcode = (ImageView) findViewById(R.id.iv_qcode);
//        qrcode1.setImageBitmap(QRCode.createQRCode("http://www.tmtpost.com/2536837.html"));
//        qrcode2.setImageBitmap(QRCode.createQRCodeWithLogo2("http://www.jianshu.com/users/4a4eb4feee62/latest_articles", 500, drawableToBitmap(getResources().getDrawable(R.drawable.head))));
//        qrcode3.setImageBitmap(QRCode.createQRCodeWithLogo3("http://www.jianshu.com/users/4a4eb4feee62/latest_articles", 500, drawableToBitmap(getResources().getDrawable(R.drawable.head))));
//        qrcode4.setImageBitmap(QRCode.createQRCodeWithLogo4("http://www.jianshu.com/users/4a4eb4feee62/latest_articles", 500, drawableToBitmap(getResources().getDrawable(R.drawable.head))));
//        qrcode5.setImageBitmap(QRCode.createQRCodeWithLogo5("http://www.jianshu.com/users/4a4eb4feee62/latest_articles", 500, drawableToBitmap(getResources().getDrawable(R.drawable.head))));
//        qrcode6.setImageBitmap(QRCode.createQRCodeWithLogo6("http://www.jianshu.com/users/4a4eb4feee62/latest_articles", 500, drawableToBitmap(getResources().getDrawable(R.drawable.head))));
        bp = QRCode.createQRCodeWithLogo5(qrUrl, 500, drawableToBitmap(getResources().getDrawable(R.mipmap.ic_launcher)));
        iv_qcode.setImageBitmap(bp);
        intiRG();
        bt_item = (Button) findViewById(R.id.bt_item);
        bt_item.setOnClickListener(this);
        lv_item = (ListView) findViewById(R.id.lv_item);
        adapter = new LvAdapter();
        lv_item.setAdapter(adapter);
        tv_num = (TextView) findViewById(R.id.tv_num);
        tv_totalCash = (TextView) findViewById(R.id.tv_totalCash);
        ll_view = findViewById(R.id.ll_view);
        ll_item1 = findViewById(R.id.ll_item1);
        ll_item2 = findViewById(R.id.ll_item2);
    }


    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {

            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            MyRecommend item = list.get(position);
            sb.delete(0, sb.length());
            View view = getLayoutInflater().inflate(R.layout.lv_recommend_item, null);

            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            sb.append(item.getUserName());
            sb.replace(3, 7, "XXXX");
            tv_name.setText(sb.toString());
            TextView tv_createTime = (TextView) view.findViewById(R.id.tv_createTime);
            tv_createTime.setText(item.getCreateTime().substring(0, 10));
            return view;
        }
    }

    /**
     * 初始化单选框
     */
    private void intiRG() {
        rg_item = (RadioGroup) findViewById(R.id.rg_item);
        rb_item1 = (RadioButton) findViewById(R.id.rb_item1);
        rb_item1.setChecked(true);
        rb_item2 = (RadioButton) findViewById(R.id.rb_item2);
        rg_item.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_item1) {
//                    ToastUtils.getInstanc(mContent).showToast("我的二维码");
                    lay_1.setVisibility(View.VISIBLE);
                    lay_2.setVisibility(View.GONE);
                } else {
//                    ToastUtils.getInstanc(mContent).showToast("已成功推荐");
                    lay_1.setVisibility(View.GONE);
                    lay_2.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void intiData() {

        intent = getIntent();
        qrUrl = (String) SharedPreferencesUtil.getParam(mContent, "qrUrl", "");

        GetRecommend();
    }

    /**
     * 获取我的成功推荐
     */
    private void GetRecommend() {
        String url = API.GetRecommend + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("page", page);
//        params.addFormDataPart("pageSize", 10);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {

                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);

                    String recommendstr = data.getString("recommend");
                    JSONObject recommend = JSONObject.parseObject(recommendstr);
                    int num = recommend.getIntValue("num");
                    tv_num.setText(num + "人");
                    double totalCash = recommend.getDoubleValue("totalCash");
                    tv_totalCash.setText(MyUtils.getdouble(totalCash * 10) + "元");

                    String userListstr = recommend.getString("userList");
                    list.addAll(JSONObject.parseArray(userListstr, MyRecommend.class));
                    if(list.size()==0)
                    {
                        ll_item1.setVisibility(View.GONE);
                        ll_item2.setVisibility(View.GONE);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_item:

                ll_view.setDrawingCacheEnabled(true);
                ll_view.buildDrawingCache();
                bp = Bitmap.createBitmap(ll_view.getDrawingCache());
                wxShare();
                break;
        }
    }

    /**
     * 分享图片
     */
    private void wxShare() {
        WXImageObject wxImageObject = new WXImageObject(bp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //设置缩略图
        Bitmap mBp = Bitmap.createScaledBitmap(bp, 120, 120, true);
        bp.recycle();
        msg.thumbData = bmpToByteArray(mBp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");//  transaction字段用
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        BaseApp.msgApi.sendReq(req);
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
